package com.example.shopingcenter.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.shopingcenter.DateBase.ShoppingDbHelper;
import com.example.shopingcenter.MainAllFragActivity;
import com.example.shopingcenter.MyApplication;
import com.example.shopingcenter.R;
import com.example.shopingcenter.enity.CartInfo;
import com.example.shopingcenter.enity.GoodsInfo;

import java.util.HashMap;
import java.util.List;

public class ShoppingCartActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_title, tv_count;
    private LinearLayout ll_cart;
    private ShoppingDbHelper mdbHelper;
    private List<CartInfo> mCartlist;
    private HashMap<Integer, GoodsInfo> mGoodsMap = new HashMap<>();
    private TextView tv_totalpricec;
    private LinearLayout ll_empty,top_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);

        tv_title = findViewById(R.id.tv_title);
        tv_totalpricec = findViewById(R.id.totlaprice);
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.btncomplete).setOnClickListener(this);
        findViewById(R.id.btn_gotoshoping).setOnClickListener(this);
        findViewById(R.id.btnclear).setOnClickListener(this);
        tv_title.setText("购物车");
        ll_cart = findViewById(R.id.ll_cart);
        ll_empty = findViewById(R.id.ll_empty);

        tv_count = findViewById(R.id.tv_count);
         top_content = findViewById(R.id.top_content);
        tv_count.setText(String.valueOf(MyApplication.getmApp().goodsCount));

        mdbHelper = ShoppingDbHelper.getDbHelper(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        showCart();
    }

    private void showCart() {
        //移除下面的子视图
        ll_cart.removeAllViews();
        mCartlist = mdbHelper.queryAllCartInfo();
        //查询数据库中的所有商品记录
        if (mCartlist.size() == 0) {
            return;
        }
        for (CartInfo info : mCartlist) {
            //根据商品编号查询数据库中的商品记录
            GoodsInfo goods = mdbHelper.queryGoodsInfoById(info.goodsId);
            mGoodsMap.put(info.goodsId, goods);

//获取布局文件item_cart.xml的根视图

            View view = LayoutInflater.from(this).inflate(R.layout.item_cart, null);
            ImageView iv_thumb = view.findViewById(R.id.iv_thumb);
            TextView tv_name = view.findViewById(R.id.tv_name);
            TextView tv_descp = view.findViewById(R.id.tv_descp);
            TextView tv_count = view.findViewById(R.id.tv_count);
            TextView tvprice = view.findViewById(R.id.tvprice);
            TextView tv_sum = view.findViewById(R.id.tv_sum);

            iv_thumb.setImageURI(Uri.parse(goods.picPath));
            tv_name.setText(goods.name);
            tv_descp.setText(goods.description);
            tv_count.setText(String.valueOf(info.count));
            tvprice.setText(String.valueOf((int) goods.price));
            tv_sum.setText(String.valueOf((int) (info.count * goods.price)));

//给商品添加长按事件，长按商品行就删除该商品
            view.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
                    builder.setMessage("是否从购物车删除" + goods.name + "?");
                    builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //移除当前视图
                            ll_cart.removeView(view);
                            //删除该商品
                            deleteGoods(info);

                        }
                    });
                    builder.setNegativeButton("否", null);
                    builder.create().show();
                    return true;
                }
            });
view.setOnClickListener(v->{
    Intent intent=new Intent(ShoppingCartActivity.this,ShoppingDetalsActivity.class);
    intent.putExtra("goods_id",goods.id);
    startActivity(intent);
});

            ll_cart.addView(view);
        }
        refreshTotalPrice();
        //重新计算购物车中的商品总金额
    }

    private void deleteGoods(CartInfo info) {
        MyApplication.getmApp().goodsCount -= info.count;
        mdbHelper.deleteCartInfoByGoodsId(info.goodsId);
        //从购物车的数据库中删除商品
        CartInfo removed = null;
//从购物车的列表中删除商品
        for (CartInfo cartInfo : mCartlist) {
            if (cartInfo.goodsId == info.goodsId) {
                removed = cartInfo;
                break;

            }
        }
        mCartlist.remove(removed);
        showCount();
        //显示最新商品数量
        Toast.makeText(this, "已从购物车删除"+mGoodsMap.get(info.goodsId).name, Toast.LENGTH_SHORT).show();
        mGoodsMap.remove(info.goodsId);

        refreshTotalPrice();
        //刷新购物车里的总金额

    }

    //显示购物车图标中的商品数量
    private void showCount() {
        tv_count.setText(String.valueOf(MyApplication.getmApp().goodsCount));
        //购物车没有商品显示空空如也
        if (MyApplication.getmApp().goodsCount==0){
            ll_empty.setVisibility(View.VISIBLE);
            top_content.setVisibility(View.GONE);
            ll_cart.removeAllViews();
        }else {
            ll_empty.setVisibility(View.GONE);
            top_content.setVisibility(View.VISIBLE);
        }
    }

    //重新计算购物车里的总金额
    private void refreshTotalPrice() {
        int totalprice = 0;
        for (CartInfo info : mCartlist) {
            GoodsInfo goods = mGoodsMap.get(info.goodsId);
            totalprice += goods.price * info.count;


        }
        tv_totalpricec.setText(String.valueOf(totalprice));


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.btnclear:
               mdbHelper.deleteAllCartInfo();
               MyApplication.getmApp().goodsCount=0;
               showCount();
                Toast.makeText(this, "购物车已清空", Toast.LENGTH_SHORT).show();

                break;
            case R.id.btncomplete:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("结算商品");
                builder.setMessage("抱歉，支付功能尚未开通，请下次再来");
                builder.setNegativeButton("确定",null);
                builder.create().show();

                break;
            case R.id.btn_gotoshoping:
                Intent intent=new Intent(ShoppingCartActivity.this, MainAllFragActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
        }
    }
}